<?php

namespace app\admin\model\share;

use addons\shopro\model\Order;
use addons\shopro\model\UserWalletLog;
use app\admin\model\order\Appaccount;
use app\admin\model\order\AppManage;
use app\admin\model\order\OrderBill;
use app\common\library\IM;
use app\common\model\AdvertPriceLog;
use app\common\model\ShareConfig;
use app\admin\model\share\Reward as ShareReward;
use app\admin\model\share\Money as ShareMoney;
use app\common\model\MoneyLog;
use addons\shopro\model\User;
use app\common\model\ShareUserRoleLog;
use think\Db;

class CommonShare
{
    // 上级用户晋级
    public function promotion_save($user_id, $role, $role_type)
    {
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户

        if (empty($user)) {
            return 0;
        }
        // 最高等级结束
        if ($user->role == 7) {
            return 0;
        }

        if ($role_type == 1) {
            $temp_role = $user->role1;
            if ($temp_role < $role) {
                $user->role1 = $role;
                $user->save();
            }
        }

        if ($role_type == 2) {
            $temp_role = $user->role2;
            if ($temp_role < $role) {
                $user->role2 = $role;
                $user->save();
            }
        }

        if ($role_type == 3) {
            $temp_role = $user->role3;
            if ($temp_role < $role) {
                $user->role3 = $role;
                $user->save();
            }
        }

        // 上级用户
        $temp_user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if ($temp_user->role >= 1 && $temp_user->role1 >= $temp_user->role &&
            $temp_user->role2 >= $temp_user->role &&
            $temp_user->role3 >= $temp_user->role) {
            $temp_add_role = bcadd($user->role, 1);
            $sharerule = Db::name("config")->where(['name' => 'sharerule','group'=>'basic'])->find();
            $is_rule = empty($sharerule) ? 'amount' : $sharerule['value'];
            if($is_rule == 'amount'){
                $ShareConfig = ShareConfig::where(['role' => $temp_add_role, 'type' => 2])->find();
                if (!empty($ShareConfig) && $user->amount >= (int)$ShareConfig['reward']) {
                    $temp_user->role = bcadd($user->role, 1);
                    $temp_user->save();
                    ShareUserRoleLog::create(['user_id' => $user_id, 'before_role' => $user->role, 'after_role' => $temp_user->role, 'before_amount' => $user->amount, 'after_amount' => $user->amount, 'memo' => '自动变更级别']);

                }
            } else {
                $ShareConfig = ShareConfig::where(['role' => $temp_add_role, 'type' => 7])->find();
                if (!empty($ShareConfig) && $user->achievement >= (int)$ShareConfig['reward']) {
                    $temp_user->role = bcadd($user->role, 1);
                    $temp_user->save();
                    ShareUserRoleLog::create(['user_id' => $user_id, 'before_role' => $user->role, 'after_role' => $temp_user->role, 'before_amount' => $user->amount, 'after_amount' => $user->amount, 'memo' => '自动变更级别']);
                }
            }

        }
        return $this->promotion_save($user->parent_id, $temp_user->role, $user->role_type);
    }

    // 上级用户降级//qi11.11
    public function promotion_dow($user_id, $role_type, $is_dow = 0, $low_user_id)
    {
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) {
            return 0;
        }
        if ($user_id == 1) {
            $s = '%/' . 1;
        } else {
            $s = '%/' . $user_id . '/%';
        }
        $sonShareCount = (new ShareUser())->where('role_url', 'like', $s)->where(['is_delete' => 0])
            ->where('role > 0')
            ->count();
        $user->amount = $sonShareCount + 1;
        $user->save();
        if ($is_dow == 0) {

            return $this->promotion_dow($user->parent_id, $user->role_type, $is_dow, $low_user_id);
        }

        //手动设置的级别，不做降级
        if ($user->manual_role == 1) {
            return $this->promotion_dow($user->parent_id, $user->role_type, $is_dow, $low_user_id);
        }
        //级别不能小于默认级别
        if ($user->role <= $user->default_role) {
            if ($user_id == 1) {
                return 0;
            }
            return $this->promotion_dow($user->parent_id, $user->role_type, $is_dow, $low_user_id);
        }
        $s = '%/' . $low_user_id . '/%';
        $sonShareAll = (new ShareUser())->where('role_url', 'like', $s)->whereOr(['user_id' => $low_user_id])
            ->order("role desc")
            ->find();
        if ($role_type == 1) {

            $temp_role = $user->role1;
            if ($temp_role != $sonShareAll['role']) {
                $user->role1 = $sonShareAll['role'];
                $user->save();
            }
        }

        if ($role_type == 2) {
            $temp_role = $user->role2;
            if ($temp_role != $sonShareAll['role']) {
                $user->role2 = $sonShareAll['role'];
                $user->save();
            }
        }

        if ($role_type == 3) {
            $temp_role = $user->role3;
            if ($temp_role != $sonShareAll['role']) {
                $user->role3 = $sonShareAll['role'];
                $user->save();
            }
        }

        // 上级用户
        $temp_user = (new ShareUser())->get(['user_id' => $user_id]); // 重新查询


        $ShareConfig = ShareConfig::where(['role' => $temp_user->role, 'type' => 2])->find();
        $ShareConfigList = ShareConfig::where(['type' => 2])->select();
        //三条线的级别和人数 有一个不够降级
        if ($user_id == 20224) {
            file_put_contents($user_id . 'tt.txt', $temp_user->role . "_" . $temp_user->role1 . "_" . $temp_user->role2 . "_" . $temp_user->role3 . "_" . $user->amount . "_" . (int)$ShareConfig['reward']);
        }
        $str = '退单用户降级日志：';
        $is_dow = 0;
        if ((($temp_user->role - $temp_user->role1) > 1 ||
                ($temp_user->role - $temp_user->role2) > 1 ||
                ($temp_user->role - $temp_user->role3) > 1) || ($user->amount < (int)$ShareConfig['reward'])) {
            $a = $temp_user->role1;
            $b = $temp_user->role2;
            $c = $temp_user->role3;
            $d = $a < $b ? ($a > $c ? $c : $a) : ($b > $c ? $c : $b);
            $r = $d + 1;//通过顶级判断
            $p = 0;//通过人数判断

            $sharerule = Db::name("config")->where(['name' => 'sharerule','group'=>'basic'])->find();
            $is_rule = empty($sharerule) ? 'amount' : $sharerule['value'];
            if($is_rule == 'amount') {
                foreach ($ShareConfigList as $k => $v) {

                    if ($user->amount > $v['reward']) {
                        continue;
                    } else {
                        $p = $v['role'] - 1;
                    }
                }
                $end_role = $r > $p ? $p : $r;
                $ro = $end_role > $temp_user->default_role ? $end_role : $temp_user->default_role;
                $temp_user->role = $ro;
                $temp_user->save();
            }else{
                $ShareConfig = ShareConfig::where(['type' => 7])->select();
                foreach ($ShareConfig as $k => $v) {

                    if ($user->achievement > $v['reward']) {
                        continue;
                    } else {
                        $y = $v['role'] - 1;
                    }
                }
                $end_role = $r > $y ? $y : $r;
                $ro = $end_role > $temp_user->default_role ? $end_role : $temp_user->default_role;
                $temp_user->role = $ro;
                $temp_user->save();
            }
            $str .= $temp_user->user_id . '从' . $temp_user->role . "将到" . $ro . "___";
            $is_dow = 1;
        }
        log_print($str);
        return $this->promotion_dow($user->parent_id, $user->role_type, $is_dow, $user->user_id);
    }

    public function chageTeamSum($user_id, $role_type, $low_user_id, $one = 0)
    {
        file_put_contents("jd11.txt", $user_id);
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) {
            return 0;
        }
        if ($user_id == 0) {
            return 0;
        }
        if ($user_id == 1) {
            $s = '%/' . 1;
        } else {
            $s = '%/' . $user_id . '/%';
        }
        $sonShareCount = (new ShareUser())->where('role_url', 'like', $s)->where(['is_delete' => 0])
            ->where('role > 0')
            ->count();
        $user->amount = $sonShareCount + 1;
        $user->save();

        $s = '%/' . $low_user_id . '/%';
        $sonShareAll = (new ShareUser())->where('role_url', 'like', $s)->whereOr(['user_id' => $low_user_id])
            ->order("role desc")
            ->find();
        file_put_contents($one . "jd.txt", $user_id . "_" . $low_user_id . "_" . $role_type . (new ShareUser())->getLastSql());
        if ($role_type == 1) {
            if (!$sonShareAll || $one == 1) {
                $user->role1 = 0;
                $user->save();
            } else {
                $temp_role = $user->role1;
                if ($temp_role != $sonShareAll['role']) {
                    $user->role1 = $sonShareAll['role'];
                    $user->save();
                }
            }

        }

        if ($role_type == 2) {
            if (!$sonShareAll || $one == 1) {
                $user->role1 = 0;
                $user->save();
            } else {
                $temp_role = $user->role2;
                if ($temp_role != $sonShareAll['role']) {
                    $user->role2 = $sonShareAll['role'];
                    $user->save();
                }
            }

        }

        if ($role_type == 3) {
            if (!$sonShareAll || $one == 1) {
                $user->role1 = 0;
                $user->save();
            } else {
                $temp_role = $user->role3;
                if ($temp_role != $sonShareAll['role']) {
                    $user->role3 = $sonShareAll['role'];
                    $user->save();
                }
            }

        }
        return $this->chageTeamSum($user->parent_id, $user->role_type, $user->user_id);
    }

    public function add_share_order($order_id, $goods_id, $user_id)
    {
        if (empty($goods_id)) {
//            \think\log::error('goods_id不能为空');
            return 0;
        }
        $shopro_order = (new Order())->where(['id' => $order_id])->find();
        if (empty($shopro_order)) {
            //            \think\log::error('shopro_order不能为空');
            return 0;
        }

        if ($shopro_order['status'] != 1) {
            //           \think\log::error('status 不能为1');
            return 0;
        }
        if ($shopro_order['user_id'] != $user_id) {
            //          \think\log::error('user_id 不一致');
            return 0;
        }
        if ($shopro_order['is_share'] != 0) {
            //         \think\log::error('is_share 不一致');
            return 0;
        }
        if ($shopro_order['one_day'] != 5) {//只有等于5的分配
            //         \think\log::error('is_share 不一致');
            return 0;
        }
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) { // 未添加 添加分销商
//            \think\log::error('user 为空');
            return 0;
        }
        /* $ShareConfig = ShareConfig::where(['goods_id' => $goods_id, 'type' => 1])->find();
         if (empty($ShareConfig)) {
             $shopro_order->is_share = 1;
             $shopro_order->save();
             return 1;
         }*/
        //分享不产生收益
        $pattern = Db::name("config")->where(['name'=>'pattern'])->value('value');
        $t_price = Db::name("config")->where(['name'=>'t_price'])->value('value');
        if($shopro_order['is_volume_val'] != 1){
            if($pattern == 3 && $shopro_order['pay_type'] == 'shopping'){
                $shopro_order['pay_fee'] = $t_price;
                $shopro_order['goods_amount'] = $t_price;

            }

        $ShareReward = ShareReward::where(['order_id' => $order_id])->find();
        if (!empty($ShareReward)) {
            return 0;
        }

        //$proportion = explode(",", $ShareConfig->reward);

        if($pattern == 1){
            $ShareConfig1 = ShareConfig::where(['type' => 6, 'role' => 1])->find();
            $ShareConfig2 = ShareConfig::where(['type' => 6, 'role' => 2])->find();
            $ShareConfig3 = ShareConfig::where(['type' => 6, 'role' => 3])->find();
            $ShareConfig4 = ShareConfig::where(['type' => 6, 'role' => 4])->find();
            $ShareConfig5 = ShareConfig::where(['type' => 6, 'role' => 5])->find();
            $this->add_reward(5, round($ShareConfig5["proportion"] * $shopro_order['pay_fee'], 2), $order_id);
            $this->add_reward(4, round($ShareConfig4["proportion"] * $shopro_order['pay_fee'], 2), $order_id);
            $this->add_reward(3, round($ShareConfig3["proportion"] * $shopro_order['pay_fee'], 2), $order_id);
            $this->add_reward(2, round($ShareConfig2["proportion"] * $shopro_order['pay_fee'], 2), $order_id);
            $this->add_reward(1, round($ShareConfig1["proportion"] * $shopro_order['pay_fee'], 2), $order_id);
        }elseif($pattern == 2){
            $ShareConfig1 = ShareConfig::where(['type' => 8, 'role' => 1])->find();
            $ShareConfig2 = ShareConfig::where(['type' => 8, 'role' => 2])->find();
            $ShareConfig3 = ShareConfig::where(['type' => 8, 'role' => 3])->find();
            $ShareConfig4 = ShareConfig::where(['type' => 8, 'role' => 4])->find();
            $ShareConfig5 = ShareConfig::where(['type' => 8, 'role' => 5])->find();
            $ShareConfig6 = ShareConfig::where(['type' => 8, 'role' => 6])->find();
            $ShareConfig7 = ShareConfig::where(['type' => 8, 'role' => 7])->find();
            $this->add_reward_two(13, round($ShareConfig7["proportion"] * $shopro_order['pay_fee'], 2), $order_id,7);
            $this->add_reward_two(12, round($ShareConfig6["proportion"] * $shopro_order['pay_fee'], 2), $order_id,6);
            $this->add_reward_two(11, round($ShareConfig5["proportion"] * $shopro_order['pay_fee'], 2), $order_id,5);
            $this->add_reward_two(10, round($ShareConfig4["proportion"] * $shopro_order['pay_fee'], 2), $order_id,4);
            $this->add_reward_two(9, round($ShareConfig3["proportion"] * $shopro_order['pay_fee'], 2), $order_id,3);
            $this->add_reward_two(8, round($ShareConfig2["proportion"] * $shopro_order['pay_fee'], 2), $order_id,2);
            $this->add_reward_two(7, round($ShareConfig1["proportion"] * $shopro_order['pay_fee'], 2), $order_id,1);
        }elseif($pattern == 3){
            $ShareConfig1 = ShareConfig::where(['type' => 8, 'role' => 1])->find();
            $this->add_reward_two(7, round($ShareConfig1["proportion"] * $shopro_order['goods_amount'], 2), $order_id,1);
        }

        // 零售收益
        $parent_user = (new ShareUser())->get(['user_id' => $user->inviter_id]); // 分销用户
        if (!empty($parent_user)) {
            if($pattern == 3){
                $ll_where['user_id'] = $shopro_order['user_id'];
                $ll_where['status'] = ['in', '1,2'];
                //$ll_where['goods_id'] = $shopro_order['goods_id'];
                $ll_where['one_day'] = 5;
                $ll_where['goods_amount'] = ['>',99];
                $ll_where['share_retreat'] = ['neq', 2];
                $ll_where['id'] = ['neq', $shopro_order['id']];
                $ll_data = Db::name("shopro_order")->where($ll_where)->find();
                $order_money = $shopro_order['goods_amount'];
                $user_data = Db::name("user u")
                    ->join("share_user s","u.id = s.user_id")
                    ->where('u.createtime','<',1672502400)
                    ->where(['u.id'=>$shopro_order['user_id']])
                    ->find();
                if($ll_data || $user_data['role']>0){//复购不产出零售
                    $this->add_range_three($order_id, $user['inviter_id'], $user['role'], $order_money, $goods_id,$shopro_order['goods_amount']);
                }else{
                    $ll_where2['user_id'] = $parent_user->user_id;
                    $ll_where2['status'] = ['in', '1,2'];
                    $ll_where2['one_day'] = 5;
                    $ll_where2['goods_amount'] = ['>',999];
                    $ll_where2['share_retreat'] = ['neq', 2];
                    $ll_data2 = Db::name("shopro_order")->where($ll_where2)->find();
                    $user_data = Db::name("user u")
                        ->join("share_user s","u.id = s.user_id")
                        ->where('u.createtime','<',1672502400)
                        ->where(['u.id'=>$parent_user->user_id])
                        ->find();
                    if($ll_data2 || $user_data['role']>0){//购买过1197或者是老用户
                        $discount = $this->add_role($parent_user->role);
                    }else{
                        $discount = $this->add_role_all($parent_user->role,9);
                    }
                    //$discount = $this->add_role_all($parent_user->role,9);
                    $money = bcmul($discount, $shopro_order['goods_amount'], 2);

                    $this->add_money(1, $money, $order_id, $parent_user->user_id, $parent_user->role, $goods_id, 1);
                    if($parent_user->role != 7){//直接推荐人是最高顶级不发放批发收益
                        $this->add_range_three($order_id, $parent_user->inviter_id, $parent_user->role, $order_money, $goods_id,$shopro_order['goods_amount']);
                    }
                }
            }else{
                $discount = $this->add_role($parent_user->role);
                $money = bcmul($discount, $shopro_order['pay_fee'], 2);
                $order_money = $shopro_order['pay_fee'];
                $this->add_money(1, $money, $order_id, $parent_user->user_id, $parent_user->role, $goods_id, 1);
                if($parent_user->role != 7){//直接推荐人是最高顶级不发放批发收益
                    $this->add_range($order_id, $parent_user->inviter_id, $parent_user->role, $order_money, $goods_id,$user['role']);
                }

            }



            // 批发收益



           /* if($pattern == 3 && $shopro_order['pay_fee'] < 999){
                $this->add_range_three($order_id, $parent_user->inviter_id, $parent_user->role, $shopro_order['pay_fee'], $goods_id);
            }else{
                $this->add_range($order_id, $parent_user->inviter_id, $parent_user->role, $shopro_order['pay_fee'], $goods_id);
            }*/
        }
        }
        // 未成为推广员 成为推广员
        if($pattern == 3){
            $tj_user = $this->getUserRole($user->user_id);
            if($tj_user > 0){
                $this->createGroup($tj_user,$user->user_id);
            }

            //$this->createGroup($user->inviter_id,$user->user_id);
        }

        if (!empty($user) && $user['role'] == 0) {
            if($pattern == 2){
                $upgrade_money = Db::name("config")->where(['name'=>'upgrade_money'])->value('value');
                $sum_pay_fee = Db::name("shopro_order")
                    ->where(['user_id'=>$user_id,'share_retreat'=>0])
                    ->where('status','>',0)
                    ->sum('pay_fee');
                file_put_contents("kk.txt",$sum_pay_fee."__".$upgrade_money);
                if ($sum_pay_fee >= $upgrade_money) {
                    $user->role = 1;
                    $user->amount = 1;

                }
            }else{
                $user->role = 1;
                $user->amount = 1;
            }
           /* $user->role = 1;
            $user->amount = 1;*/
            if($shopro_order['pay_type'] != "shopping") {
                $user->achievement = $shopro_order['pay_fee'];
            }
            $user->save();
            ShareUserRoleLog::create(['user_id' => $user_id, 'before_role' => 0, 'after_role' => 1, 'before_amount' => 0, 'after_amount' => 1, 'memo' => '自动变更级别']);
            //创建群

        } else {
            $s = '%/' . $user['user_id'] . '/%';
            $sonShareAll = (new ShareUser())->where('role_url', 'like', $s)->where(['is_delete' => 0])
                ->where('role > 0')
                ->count();
            $user->amount = $sonShareAll + 1;
            //$user->amount = bcadd($user['amount'], 1);
            if($shopro_order['is_volume_val'] != 1) {
                $user->achievement = bcadd($user['achievement'],$shopro_order['pay_fee'],2);
            }

            $user->save();
        }
        // 上级数量加 1
        if (!empty($user['role_url'])) {
            $parents = explode('/', $user['role_url']);
            foreach ($parents as $key => $value) {
                if ($key >= 1) {
                    $this->sum_amount($parents[$key],$shopro_order['pay_fee'],$shopro_order['is_volume_val']);
                }
            }
        }
        // 上级及以上记录最高级别 晋级
        $this->promotion_save($user->parent_id, $user->role, $user->role_type);
        $shopro_order->is_share = 2;
        $shopro_order->save();
        return 1;
    }
    /**
     * 查询用户上级第一个大于等于二星的用户
     */
    public function getUserRole($user_id){
        $user_data = Db::name("share_user")->where(['user_id'=>$user_id])->find();
        if(!$user_data){
            return 0;
        }
        if($user_data['role'] >= 4){
            return $user_id;
        }else{
            return self::getUserRole($user_data['parent_id']);
        }
    }
    /**
     * @return void
     * 创建群
     */
    public function createGroup($inviter_id,$user_id){

        $uid = $inviter_id;
        $log_data = Db::name("chat_create_log")->where(['user_id'=>$uid,'chat_type'=>2,'type'=>2])->find();
        if(!$log_data){
            $data = (new \app\common\library\IM)->creatre_group($uid,1);
            if($data['ErrorCode'] != 0){
               // $this->error($data['ErrorInfo']);
            }else{
                $id_data = [
                    'user_id' => $uid,
                    'chat_obj' => $data['GroupId'],
                    'chat_type' => 2,
                    'type' => 2,
                    'create_time' => time()
                ];
                //同一用户，同一聊天对象只存储一次
                Db::name('chat_create_log')->insert($id_data);
                $this->addMembers($data['GroupId'],$user_id);
                $this->add_group_msg($data['GroupId'],$uid);
               // $this->success('成功');
            }
        }else{
            $this->addMembers($log_data['chat_obj'],$user_id);
            // $this->add_group_msg($log_data['chat_obj']);
           //return ;
        }

    }
    /**
     * 添加好友
     */
    public function addMembers($GroupId,$UserID){
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app_id = (new AppManage())->getAppId($url['value']);
        (new \app\common\library\IM)->add_members($GroupId,$app_id['id'] . '_' . $UserID);
    }

    /**
     * @param $GroupId
     * @param $uid
     * @return void
     * 发信息
     */
    public function add_group_msg($GroupId,$uid){
        (new \app\common\library\IM)->add_group_msg($GroupId,'创富群创建成功',$uid);
    }
    public function parent_promotin($user_id)
    {
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        // 上级数量加 1
        if (!empty($user['role_url'])) {
            $parents = explode('/', $user['role_url']);
            foreach ($parents as $key => $value) {
                if ($key >= 1) {
                    $this->sum_amount($parents[$key],0);
                }
            }
        }
        // 上级及以上记录最高级别 晋级
        $this->promotion_save($user->parent_id, $user->role, $user->role_type);
    }

    private function add_reward($type, $money, $order_id)
    {
        $shoproorder = Db::table('shopro_order')->where(['id' => $order_id])->find();
        $user_flags = Db::table('share_user_flags')->where(['user_id' => $shoproorder['user_id']])->find();
        $role = $type;
        if ($type == 4) {
            $role = 3;
        } elseif ($type == 5) {
            $role = 4;
        }
        $con_ddata = Db::name("share_config")->where(['role' => $role, 'type' => 3])->find();
        $price_gg = 1 - $con_ddata['reward'];
        $mutual_money_bl = $con_ddata['reward'];

        $reward = new ShareReward();

        $reward->user_flags = isset($user_flags['user_flags']) ? $user_flags['user_flags'] : '';
        $reward->money = bcmul($price_gg, $money, 2);
        $reward->type = $type;
        $reward->order_id = $order_id;
        $reward->addtime = time();
        $reward->mutual_money = bcmul($mutual_money_bl, $money, 2);
        $reward->save();
    }
    private function add_reward_two($type, $money, $order_id,$role)
    {
        $shoproorder = Db::table('shopro_order')->where(['id' => $order_id])->find();
        $user_flags = Db::table('share_user_flags')->where(['user_id' => $shoproorder['user_id']])->find();
        //$role = $type;
        $con_ddata = Db::name("share_config")->where(['role' => $role, 'type' => 3])->find();
        $price_gg = 1 - $con_ddata['reward'];
        $mutual_money_bl = $con_ddata['reward'];

        $reward = new ShareReward();

        $reward->user_flags = isset($user_flags['user_flags']) ? $user_flags['user_flags'] : '';
        $reward->money = bcmul($price_gg, $money, 2);
        $reward->type = $type;
        $reward->order_id = $order_id;
        $reward->addtime = time();
        $reward->mutual_money = bcmul($mutual_money_bl, $money, 2);
        $reward->save();
    }

    // type 1 直推 2极差 3日创收 4周创收
    private function add_money($type, $money, $order_id, $user_id, $role, $goods_id, $is_one = 0)
    {
//        \think\log::error(json_encode([$type, $money, $order_id]));
        if (isset($money) && $money != "0.00") {
            //获取不通等级分给佣金的比例 qi11.3
            $con_ddata = Db::name("share_config")->where(['role' => $role, 'type' => 3])->find();
            //$user->price += bcmul(0.9, $money, 2);
            $price_bl = 1 - $con_ddata['reward'];
            $mutual_money_bl = $con_ddata['reward'];

            $ShareMoney = new ShareMoney();
            //$ShareMoney->money = $money;
            $ShareMoney->money = bcmul($price_bl, $money, 2);
            $ShareMoney->mutual_money = bcmul($mutual_money_bl, $money, 2);
            $ShareMoney->type = $type;
            $ShareMoney->order_id = $order_id;
            $ShareMoney->user_id = $user_id;
            $ShareMoney->goods_id = $goods_id;
            $ShareMoney->role = $role;
            $ShareMoney->addtime = time();
            if ($type == 1 || $type == 2) {
                $ShareMoney->is_grant = 0;
            }
            $ShareMoney->save();
            /*qi11.9
             * $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
            $old_mutual_money = $user->mutual_money;

            $user->price += bcmul($price_bl, $money, 2);
            $user->total_price += $money;
            $user->mutual_money += bcmul($mutual_money_bl, $money, 2);
            $user->save();
            if(bcmul($mutual_money_bl, $money, 2) > 0){
                User::mutual(bcmul($mutual_money_bl, $money, 2), $user_id, 'mutual_add', $order_id, '', [], $old_mutual_money);
            }
            $after = bcmul($price_bl, $money, 2) + $user->price;
            $cz_type = 0;
            if ($is_one == 1) {
                $memo = '零售收益';
                $cz_type = 10;
            } elseif ($is_one == 2) {
                $memo = '批发收益';
                $cz_type = 11;
            }
            MoneyLog::create(['user_id' => $user_id, 'money' => bcmul($price_bl, $money, 2), 'before' => $user->price, 'after' => $after, 'type' => $cz_type, 'memo' => $memo, 'order_id'=>$order_id]);
        */
        }
    }

    // 奖励级别 // "1":'推广员',"2":'代言人',"3":'一星网店经销商',"4":'二星网店经销商',"5":'银牌经销商',"6":'金牌经销商',"7":'钻石经销商'
    private function add_role($role)
    {
        $ShareConfig = ShareConfig::where(['goods_id' => 0, 'type' => 0, 'role' => $role])->find();
        if (empty($ShareConfig)) {
            $discount = 0;
        } else {
            $discount = $ShareConfig->proportion;
        }
        return $discount;
    }
    public function add_role_all($role,$type)
    {
        $ShareConfig = ShareConfig::where(['type' => $type, 'role' => $role])->find();
        if (empty($ShareConfig)) {
            $discount = 0;
        } else {
            $discount = $ShareConfig->proportion;
        }
        return $discount;
    }

    /**
     * order_id 订单id
     * user_id 用户id
     * role 上一级等级
     * pay_fee 支付金额
     */
    private function add_range($order_id, $user_id, $role, $pay_fee, $goods_id,$tz_role=0)
    {
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) {
            return 0;
        }
        if($tz_role == 7){
            return 0;
        }
        // 最高等级结束
        if ($user->role == 7) {
            if ($user->role == $role) {
                return 0;
            } else {
                $discount1 = $this->add_role($role);
                $discount2 = $this->add_role($user->role);
                $discount = bcsub($discount2, $discount1, 3);
                if ($discount <= 0) {
                    return 0;
                }
                $money = bcmul($discount, $pay_fee, 2);
                $this->add_money(2, $money, $order_id, $user->user_id, $user->role, $goods_id, 2);
                return 0;
            }

        }
        // 同级下级不奖励
        if ($user->role <= $role) {
            return $this->add_range($order_id, $user->inviter_id, $role, $pay_fee, $goods_id);
        } else {
            $discount1 = $this->add_role($role);
            $discount2 = $this->add_role($user->role);
            $discount = bcsub($discount2, $discount1, 3);
            $money = bcmul($discount, $pay_fee, 2);
            $this->add_money(2, $money, $order_id, $user->user_id, $user->role, $goods_id, 2);
            return $this->add_range($order_id, $user->inviter_id, $user->role, $pay_fee, $goods_id);
        }
    }
    /*private function add_range($order_id, $user_id, $role, $pay_fee, $goods_id)
    {
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) {
            return 0;
        }
        // 最高等级结束
        if ($user->role == 7) {
            if ($user->role == $role) {
                return 0;
            } else {
                $discount1 = $this->add_role($role);
                $discount2 = $this->add_role($user->role);
                $discount = bcsub($discount2, $discount1, 3);
                if ($discount <= 0) {
                    return 0;
                }
                $money = bcmul($discount, $pay_fee, 2);
                $this->add_money(2, $money, $order_id, $user->user_id, $user->role, $goods_id, 2);
                return 0;
            }

        }
        // 同级下级不奖励
        if ($user->role <= $role) {
            return $this->add_range($order_id, $user->inviter_id, $role, $pay_fee, $goods_id);
        } else {
            $discount1 = $this->add_role($role);
            $discount2 = $this->add_role($user->role);
            $discount = bcsub($discount2, $discount1, 3);
            $money = bcmul($discount, $pay_fee, 2);
            $this->add_money(2, $money, $order_id, $user->user_id, $user->role, $goods_id, 2);
            return $this->add_range($order_id, $user->inviter_id, $user->role, $pay_fee, $goods_id);
        }
    }*/

    private function add_range_three($order_id, $user_id, $role, $pay_fee, $goods_id,$goods_amount)
    {
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) {
            return 0;
        }
        $discount = 0;
        if($goods_amount >999){
            $type = 12;
        }else{
            $type = 12;
        }
        // 最高等级结束
        if ($user->role == 7) {
            if ($user->role == $role) {
                return 0;
            } else {
                /*$discount1 = $this->add_role($role);
                $discount2 = $this->add_role($user->role);
                $discount = bcsub($discount2, $discount1, 3);
                if ($discount <= 0) {
                    return 0;
                }*/


                for($i = $role+1;$user->role >= $i;$i++){

                    $discount1 = $this->add_role_all($i,$type);
                    $discount += $discount1;
                }

                $money = bcmul($discount, $pay_fee, 2);
                $this->add_money(2, $money, $order_id, $user->user_id, $user->role, $goods_id, 2);
                return 0;
            }

        }
        // 同级下级不奖励
        if ($user->role <= $role) {
            return $this->add_range_three($order_id, $user->inviter_id, $role, $pay_fee, $goods_id,$goods_amount);
        } else {
            for($i = $role+1;$user->role >= $i;$i++){

                $discount1 = $this->add_role_all($i,$type);
                $discount += $discount1;
            }
            $money = bcmul($discount, $pay_fee, 2);
            $this->add_money(2, $money, $order_id, $user->user_id, $user->role, $goods_id, 2);
            return $this->add_range_three($order_id, $user->inviter_id, $user->role, $pay_fee, $goods_id,$goods_amount);
        }
    }
    private function add_range_three_two($order_id, $user_id, $role, $pay_fee, $goods_id,$goods_amount)
    {
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) {
            return 0;
        }
        $discount = 0;
        if($goods_amount >999){
            $type = 12;
        }else{
            $type = 12;
        }
        // 最高等级结束
        if ($user->role == 7) {
            if ($user->role == $role) {
                return 0;
            } else {
                /*$discount1 = $this->add_role($role);
                $discount2 = $this->add_role($user->role);
                $discount = bcsub($discount2, $discount1, 3);
                if ($discount <= 0) {
                    return 0;
                }*/

                for($i = $role;$user->role >= $i;$i++){
                    $discount1 = $this->add_role_all($i,$type);
                    $discount += $discount1;
                }

                $money = bcmul($discount, $pay_fee, 2);
                $this->add_money(2, $money, $order_id, $user->user_id, $user->role, $goods_id, 2);
                return 0;
            }

        }
        // 同级下级不奖励
        if ($user->role <= $role) {
            return $this->add_range_three_two($order_id, $user->inviter_id, $role, $pay_fee, $goods_id,$goods_amount);
        } else {
            for($i = $role;$user->role > $i;$i++){

                $discount1 = $this->add_role_all($i,$type);
                $discount += $discount1;
            }
            $money = bcmul($discount, $pay_fee, 2);
            $this->add_money(2, $money, $order_id, $user->user_id, $user->role, $goods_id, 2);
            return $this->add_range_three_two($order_id, $user->inviter_id, $user->role, $pay_fee, $goods_id,$goods_amount);
        }
    }
    public function sum_amount($user_id,$pay_fee,$is_volume_val=0)
    {
        if ($user_id == 1) {
            $s = '%/' . $user_id;
        } else {
            $s = '%/' . $user_id . '/%';
        }
        $sonShareAll = (new ShareUser())->where('role_url', 'like', $s)->where(['is_delete' => 0])
            ->where('role > 0')
            ->count();
        $sonShareAll = $sonShareAll ?? 0;
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        // $user->amount = bcadd($user['amount'], 1);
        $user->amount = $sonShareAll + 1;
        if($is_volume_val != 1){
            $user->achievement = bcadd($user['achievement'],$pay_fee,2);
        }

        $user->save();
    }

    public function add_share_order_equity($pay_fee, $goods_id, $user_id)
    {
        if (empty($goods_id)) {
            return 0;
        }

        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) { // 未添加 添加分销商
            return 0;
        }
        $ShareConfig = ShareConfig::where(['goods_id' => $goods_id, 'type' => 1])->find();
        if (empty($ShareConfig)) {
            return 0;
        }
        $ShareConfig1 = ShareConfig::where(['type' => 6, 'role' => 1])->find();
        $ShareConfig2 = ShareConfig::where(['type' => 6, 'role' => 2])->find();
        $ShareConfig3 = ShareConfig::where(['type' => 6, 'role' => 3])->find();
        $ShareConfig4 = ShareConfig::where(['type' => 6, 'role' => 4])->find();
        $ShareConfig5 = ShareConfig::where(['type' => 6, 'role' => 5])->find();
        $this->add_reward(5, $ShareConfig5["proportion"], 0);
        $this->add_reward(4, $ShareConfig4["proportion"], 0);
        $this->add_reward(3, $ShareConfig3["proportion"], 0);
        $this->add_reward(2, $ShareConfig2["proportion"], 0);
        $this->add_reward(1, $ShareConfig1["proportion"], 0);

        /*$proportion = explode(",", $ShareConfig->reward);
        $this->add_reward(5, $proportion[0], 0);
        $this->add_reward(4, $proportion[1], 0);
        $this->add_reward(3, $proportion[2], 0);
        $this->add_reward(2, $proportion[3], 0);
        $this->add_reward(1, $proportion[4], 0);*/
        // 零售收益
        $parent_user = (new ShareUser())->get(['user_id' => $user->inviter_id]); // 分销用户
        if (!empty($parent_user)) {
            $discount = $this->add_role($parent_user->role);
            $money = bcmul($discount, $pay_fee, 2);
            $this->add_money(1, $money, 0, $parent_user->user_id, $parent_user->role, $goods_id, 1);
            // 批发收益
            $this->add_range(0, $parent_user->parent_id, $parent_user->role, $pay_fee, $goods_id);
        }

        // 未成为推广员 成为推广员
        if (!empty($user) && $user['role'] == 0) {

            $pattern = Db::name("config")->where(['name'=>'pattern'])->value('value');

            if($pattern == 2){
                $upgrade_money = Db::name("config")->where(['name'=>'upgrade_money'])->value('value');
                $sum_pay_fee = Db::name("shopro_order")
                    ->where(['user_id'=>$user_id,'share_retreat'=>0])
                    ->where('status','>',0)
                    ->sum('pay_fee');
                file_put_contents("kk.txt",$sum_pay_fee."__".$upgrade_money);
                if ($sum_pay_fee >= $upgrade_money) {
                    $user->role = 1;
                    $user->amount = 1;

                }
            }else{
                $user->role = 1;
                $user->amount = 1;
            }
           /* $user->role = 1;
            $user->amount = 1;*/
            $user->achievement = $pay_fee;
            $user->save();
        } else {
            $s = '%/' . $user['user_id'] . '/%';
            $sonShareAll = (new ShareUser())->where('role_url', 'like', $s)->where(['is_delete' => 0])
                ->where('role > 0')
                ->count();
            $user->amount = $sonShareAll + 1;
            //$user->amount = bcadd($user['amount'], 1);
            $user->achievement = bcadd($user['achievement'],$pay_fee,2);
            $user->save();
        }
        // 上级数量加 1
        if (!empty($user['role_url'])) {
            $parents = explode('/', $user['role_url']);
            foreach ($parents as $key => $value) {
                if ($key >= 1) {
                    $this->sum_amount($parents[$key],$pay_fee);
                }
            }
        }
        // 上级及以上记录最高级别 晋级
        $this->promotion_save($user->parent_id, $user->role, $user->role_type);
        return 1;
    }

    /**
     * 退单
     */
    public function Chargeback($order_id, $user_id, $order_sn = '')
    {

        //开始时间
        $start_time = date("Y-m-d 00:00:00");
        //结束时间
        $end_time = date('Y-m-d H:i:s');
        $shopro_order = (new Order())->where('createtime', 'between time', [$start_time, $end_time])->where(['id' => $order_id])->find();
        if (empty($shopro_order)) {
            return 0;
        }
        if ($shopro_order['user_id'] != $user_id) {
            return 0;
        }
        if ($shopro_order['share_retreat'] != 3) {
            return 0;
        }

        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) { // 未添加 添加分销商
            return 0;
        }
        $user->achievement = bcsub($user['achievement'],$shopro_order['pay_fee'],2);
        $user->save();
        $this->achievement_dow($user->parent_id,$shopro_order['pay_fee']);
        file_put_contents("kk.txt","tuikuan");
        // 用户金额减少
        $ShareMoney = (new ShareMoney())->where(['order_id' => $order_id])->select();
        foreach ($ShareMoney as $key => $value) {
            if (($value['type'] == 1 || $value['type'] == 2) && $value['is_grant'] == 0) {//qi11.9零售批发未发放处理
                continue;
            }
            $user_temp = (new ShareUser())->get(['user_id' => $value['user_id']]); // 分销用户

            //$after = $user_temp->price - bcmul(0.9, $value['money'], 2);
            if ($value['type'] == 3 || $value['type'] == 4) {//广告创收
                $before = $user_temp->advert_price;
                $after = $user_temp->advert_price - $value['money'];
                $user_temp->advert_price = $after;
            } else {
                $before = $user_temp->price;
                $after = $user_temp->price - $value['money'];
                $user_temp->price = $after;
            }


            $user_temp->total_price -= $value['money'];
            $user_temp->mutual_money -= $value['mutual_money'];
            $user_temp->amount = bcsub($user_temp['amount'], 1);
            $user_temp->save();
            if ($value['type'] == 1) {
                $type = 10;//零售收益
            } elseif ($value['type'] == 2) {
                $type = 11;//批发收益
            } elseif ($value['type'] == 3) {
                $type = 13;//日广告收益
                $advert_type = 1;
                $memo = '日广告收益';
            } elseif ($value['type'] == 4) {
                $type = 14;//周广告收益
                $advert_type = 2;
                $memo = '周广告收益';
            } elseif ($value['type'] == 5) {
                $type = 15;//多商户进货成本
            } elseif ($value['type'] == 6) {
                $type = 16;//多商户一星网点分佣
            }
            if ($value['type'] == 3 || $value['type'] == 4) {//广告创收
                AdvertPriceLog::create(['user_id' => $value['user_id'], 'money' => $value['money'], 'before' => $before, 'after' => $after, 'type' => $advert_type, 'memo' => $memo]);
            } else {
                MoneyLog::create(['user_id' => $value['user_id'], 'money' => $value['money'], 'before' => $before, 'after' => $after, 'type' => $type, 'memo' => '退单余额减少', 'order_id' => $order_id]);
            }

            if ($value['mutual_money'] > 0) {
                $after = $user_temp->mutual_money - $value['mutual_money'];
                UserWalletLog::create(['user_id' => $value['user_id'], 'wallet' => -$value['mutual_money'], 'wallet_type' => 'mutual', 'type' => 'mutual_add', 'before' => $user_temp->mutual_money, 'after' => $after, 'item_id' => $order_id, 'memo' => '退单余额减少', 'oper_type' => 'system', 'createtime' => time()]);
            }

        }
        (new ShareMoney())->where(['order_id' => $order_id])->delete();
        (new ShareReward())->where(['order_id' => $order_id])->delete();
        //删除分帐
        Db::name("shopro_order_bill")->where(['order_sn' => $order_sn])->delete();
        //qi11.11

        //qi11.11
        /*if ($user->role == 1) {
            $user->role = 0;
            $amount = bcsub($user['amount'], 1);
            $user->amount = ($amount < 0) ? 0 : $amount;
            $user->save();
            //上级分销商
            $parent_user = (new ShareUser())->get(['user_id' => $user->parent_id]);
            $parent_user->role = 1;
            if ($user->role_type == 1) {
                $parent_user->role1 = 0;
            }

            if ($user->role_type == 2) {
                $parent_user->role2 = 0;
            }

            if ($user->role_type == 3) {
                $parent_user->role3 = 0;
            }
            $parent_user->save();
        } else {
            $amount = bcsub($user['amount'], 1);
            $user->amount = ($amount < 0) ? 0 : $amount;
            $user->save();
        }*/

        $shopro_order->share_retreat = 2;
        $shopro_order->save();
        if ($user->role == 1) {
            $order_data = Db::name("shopro_order")
                ->where('status', 'in', [1, 2])
                ->where('id', 'not in', [$order_id])
                ->where(["share_retreat" => 0])
                ->where(["user_id" => $user_id])
                ->find();
            if (!$order_data) {//当前人降价才会调用上级降级
                if ($user->role > $user->default_role) {
                    $user->role = 0;
                    $user->save();
                }
                $this->promotion_dow($user->parent_id, $user->role_type, 1, $user->user_id);
            }

        }
        return 1;
    }
    public function achievement_dow($user_id,$order_fee){
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) {
            return 0;
        }
        $user->achievement = bcsub($user['achievement'],$order_fee,2);
        $user->save();
        return $this->achievement_dow($user->parent_id, $order_fee);
        if($user_id == 1){
            return 0;
        }
    }
    /**
     * 分账入库
     * @return void
     */
    public function orderBillAdd()
    {
        $where = [];
        $where['status'] = ['>=', 1];
        $where['one_day'] = ['in', [1, 2, 5]];
        $where['share_retreat'] = 0;
        $where['is_bill'] = 0;
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app_id = (new AppManage())->getAppId($url['value']);
        $bill_data1 = (new OrderBill())->OrderBillData(1,$app_id['id']);
        $bill_data2 = (new OrderBill())->OrderBillData(2,$app_id['id']);
        $bill_data5 = (new OrderBill())->OrderBillData(5,$app_id['id']);
        $bill_data6 = (new OrderBill())->OrderBillData(6,$app_id['id']);
        $bill_data8 = (new OrderBill())->OrderBillData(8,$app_id['id']);
        $yu_account = Db::table('shopro_order')->where($where)->order("id desc")->limit(3)->select();
        //print_r($yu_account);die();


        if (!$yu_account) {
            echo "无订单";
            return;
        }
        Db::startTrans();
        if ($yu_account) {
            foreach ($yu_account as $k => $v) {
                $bill_order_data = Db::name("shopro_order_bill")->where(["order_sn" => $v['order_sn']])->find();
                if ($bill_order_data) {
                    db('shopro_order')->where(['order_sn' => $v['order_sn']])->update(['is_bill' => 1]);
                    Db::commit();
                    continue;
                }
                $one_day_first = 1;
                if ($v['one_day'] == 1) {
                    $one_day_first = Db::name("user")->where(['id' => $v['user_id']])->value("one_day_first");
                    if ($one_day_first == 1) {
                        $bill_data = $bill_data1;
                    } else {//每月一品第一单
                        $bill_data = $bill_data6;
                    }

                } elseif ($v['one_day'] == 2) {
                    $bill_data = $bill_data2;
                } else {
                    $is_equity = Db::name("shopro_goods")->where(['id'=>$v['goods_id']])->value("is_equity");
                    if($is_equity == 1){
                        $bill_data = $bill_data8;
                    }else{
                        $bill_data = $bill_data5;
                    }
                }
                $gg_mutual_money = Db::name("share_reward")->where(['order_id' => $v['id']])->where('type', 'in', [1, 2, 3, 4, 5])->sum("mutual_money");
                $lp_mutual_money = Db::name("share_money")->where(['order_id' => $v['id']])->where('type', 'in', [1, 2])->sum("mutual_money");
                $fzArr = [];
                $con = count($bill_data);
                $sum_money = 0;
                foreach ($bill_data as $key => $fzDetail) {
                    $ins['user_id'] = $v['user_id'];
                    $ins['order_sn'] = $v['order_sn'];
                    $ins['total_amount'] = $v['total_amount'];
                    $ins['goods_type'] = (string)$fzDetail['type'];
                    if ($v['pay_type'] == 'shopping') {
                        $ins['coupon_status'] = '0';
                        $ins['type'] = '1';
                    } elseif ($v['pay_type'] == 'mutual') {
                        $ins['coupon_status'] = '0';
                        $ins['type'] = '3';
                    } elseif ($v['pay_type'] == 'wallet') {
                        if ($v['is_old'] == 0) {//钱包 coupon_status
                            $ins['coupon_status'] = '1';
                            $ins['type'] = '0';
                        } elseif ($v['is_old'] == 2) {//零批
                            $ins['coupon_status'] = '0';
                            $ins['type'] = '2';
                        } else {
                            $ins['coupon_status'] = '0';
                            $ins['type'] = '3';
                        }

                    } else {
                        $ins['coupon_status'] = '0';
                        $ins['type'] = '3';
                    }
                    $ins['percent'] = $fzDetail['proportion'];
                    echo $key . "__" . $sum_money . "/";
                    if (($con - 1) == $key) {
                        $ins['fz_money'] = round($v['total_amount'] - $sum_money, 2);
                        //$ins['fz_real_money'] = round($v['total_amount'] - $sum_money,2);
                        if ($ins['fz_money'] < 0) {
                            $fzArr[$key - 1]['fz_money'] = $fzArr[$key - 1]['fz_money'] + $ins['fz_money'];
                            //$fzArr[$key - 1]['fz_real_money'] = $fzArr[$key - 1]['fz_real_money'] + $ins['fz_real_money'];
                            $ins['fz_money'] = 0;
                            //$ins['fz_real_money'] = 0;
                        }
                    } else {
                        if ($fzDetail['calc_type'] == 1) {//互助金
                            //$fzDetail['proportion'] = '';
                            $fz_money = round($gg_mutual_money + $lp_mutual_money, 2);
                        } else {
                            $fz_money = round(($v['total_amount'] * ($fzDetail['proportion'] / 100)), 2);
                            if ($fzDetail['account_type'] == 1) {//零批
                                $fz_money = $fz_money - $lp_mutual_money;
                            } elseif ($fzDetail['account_type'] == 2) {//广告创收
                                $fz_money = $fz_money - $gg_mutual_money;
                            }

                        }
                        $ins['fz_money'] = round($fz_money, 2);
                        $sum_money += round($fz_money, 2);
                    }
                    $fz_proportion = $fzDetail['proportion'] - $fzDetail['reduse_pro'];
                    if ($fzDetail['calc_type'] == 1) {//互助金
                        $fz_real_money = round($gg_mutual_money + $lp_mutual_money, 2);
                    } else {
                        $fz_real_money = round(($v['total_amount'] * ($fz_proportion / 100)), 2);
                        if ($fzDetail['account_type'] == 1) {//零批
                            $fz_real_money = $fz_real_money - $lp_mutual_money;
                        } elseif ($fzDetail['account_type'] == 2) {//广告创收
                            $fz_real_money = $fz_real_money - $gg_mutual_money;
                        }

                    }
                    $ins['fz_real_money'] = round($fz_real_money, 2);

                    $ins['fz_type'] = $fzDetail['company_type'];
                    if ($fzDetail['calc_type'] == 1) {
                        $ins['fz_title'] = $fzDetail['name'] . "0.00";
                    } else {
                        $ins['fz_title'] = $fzDetail['name'] . $fzDetail['proportion'];
                    }

                    $ins['status'] = '0';
                    $ins['ledger_id'] = $fzDetail['id'];
                    $ins['createtime'] = time();
                    $ins['paytime'] = $v['paytime'];
                    $acc_data = (new Appaccount())->getAppAccount($app_id['id'], $fzDetail['ledger_id']);
                    if (!empty($acc_data)) {
                        $ins['fz_account'] = $acc_data['name'];
                        $ins['fz_number'] = $acc_data['code'];
                    }
                    if ($app_id) {
                        $ins['isNeedShare'] = $app_id['isNeedShare'];
                    } else {
                        $ins['isNeedShare'] = 2;
                    }

                    $fzArr[] = $ins;
                }
                $d3 = true;
                $d1 = db('shopro_order_bill')->insertAll($fzArr);
                $d2 = db('shopro_order')->where(['order_sn' => $v['order_sn']])->update(['is_bill' => 1]);
                if ($one_day_first == 0) {
                    $d3 = Db::name("user")->where(['id' => $v['user_id']])->update(['one_day_first' => 1]);
                }
                if ($d1 && $d2 && $d3) {
                    Db::commit();
                } else {
                    Db::rollback();
                }
            }
            echo 'success';
        }
    }

    public function vipBillOrder()
    {
        $where['pay_status'] = 2;
        $where['is_bill'] = 0;
        $vip_list = Db::name("vip_recharge_order")->where($where)->limit(5)->select();
        if (!$vip_list) {
            echo "无订单";
            return;
        }
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app_id = (new AppManage())->getAppId($url['value']);
        Db::startTrans();
        $bill_data = (new OrderBill())->OrderBillData(7,$app_id['id']);

        foreach ($vip_list as $k => $v) {
            $bill_order_data = Db::name("shopro_order_bill")->where(["order_sn" => $v['id'], 'goods_type' => 7])->find();
            if ($bill_order_data) {
                db('vip_recharge_order')->where(["order_sn" => $v['id'], 'goods_type' => 7])->update(['is_bill' => 1]);
                Db::commit();
                continue;
            }
            $one_day_first = 1;
            $fzArr = [];
            $con = count($bill_data);
            $sum_money = 0;
            foreach ($bill_data as $key => $fzDetail) {
                $ins['user_id'] = $v['user_id'];
                $ins['order_sn'] = $v['id'];
                $ins['total_amount'] = $v['pay_money'];
                $ins['goods_type'] = (string)$fzDetail['type'];
                if ($v['pay_type'] == 1) {
                    $ins['coupon_status'] = '1';
                    $ins['type'] = '0';
                } else {
                    echo "支付方式错误";
                    continue;
                }
                $ins['percent'] = $fzDetail['proportion'];
                echo $key . "__" . $sum_money . "/";
                if (($con - 1) == $key) {
                    $ins['fz_money'] = round($v['pay_money'] - $sum_money, 2);
                    //$ins['fz_real_money'] = round($v['total_amount'] - $sum_money,2);
                    if ($ins['fz_money'] < 0) {
                        $fzArr[$key - 1]['fz_money'] = $fzArr[$key - 1]['fz_money'] + $ins['fz_money'];
                        //$fzArr[$key - 1]['fz_real_money'] = $fzArr[$key - 1]['fz_real_money'] + $ins['fz_real_money'];
                        $ins['fz_money'] = 0;
                        //$ins['fz_real_money'] = 0;
                    }
                } else {
                    $fz_money = round(($v['pay_money'] * ($fzDetail['proportion'] / 100)), 2);
                    $ins['fz_money'] = round($fz_money, 2);
                    $sum_money += round($fz_money, 2);
                }
                //时间分账金额
                $fz_proportion = $fzDetail['proportion'] - $fzDetail['reduse_pro'];
                $fz_real_money = round(($v['pay_money'] * ($fz_proportion / 100)), 2);
                $ins['fz_real_money'] = round($fz_real_money, 2);

                $ins['fz_type'] = $fzDetail['company_type'];
                if ($fzDetail['calc_type'] == 1) {
                    $ins['fz_title'] = $fzDetail['name'] . "0.00";
                } else {
                    $ins['fz_title'] = $fzDetail['name'] . $fzDetail['proportion'];
                }

                $ins['status'] = '0';
                $ins['ledger_id'] = $fzDetail['id'];
                $ins['createtime'] = time();
                $ins['paytime'] = $v['pay_time'];
                $acc_data = (new Appaccount())->getAppAccount($app_id['id'], $fzDetail['ledger_id']);
                if (!empty($acc_data)) {
                    $ins['fz_account'] = $acc_data['name'];
                    $ins['fz_number'] = $acc_data['code'];
                }
                if ($app_id) {
                    $ins['isNeedShare'] = $app_id['isNeedShare'];
                } else {
                    $ins['isNeedShare'] = 2;
                }

                $fzArr[] = $ins;
            }
            $d1 = db('shopro_order_bill')->insertAll($fzArr);
            $d2 = db('vip_recharge_order')->where(['id' => $v['id']])->update(['is_bill' => 1]);
            if ($d1 && $d2) {
                Db::commit();
            } else {
                Db::rollback();
            }
        }
        echo 'success';
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 删除没有订单的分账和收益
     */
    public function delOrderBill()
    {
        echo "a" . PHP_EOL;
        $order_list = Db::name("shopro_order")->select();
        $vip_list = Db::name("vip_recharge_order")->select();
        //$order_list = Db::name("shopro_order")->whereTime('paytime', 'today')->select();
        $vip_sn_arr = array_column($vip_list, 'id');
        $order_sn_arr = array_column($order_list, 'order_sn');
        $order_sn_arr_t = array_merge($order_sn_arr, $vip_sn_arr);
        echo "b" . PHP_EOL;
        //删除分账
        Db::name("shopro_order_bill")->where("order_sn", 'not in', $order_sn_arr_t)->delete();
        //删除预期收益
        $order_id_arr = array_column($order_list, 'id');
        Db::name("share_reward")->where(["status" => 0])->where("order_id", 'not in', $order_id_arr)->delete();
        //删除share_money
        Db::name("share_money")->where(["is_grant" => 0])->where('type', 'in', [1, 2])->where("order_id", 'not in', $order_id_arr)->delete();
        echo "c" . PHP_EOL;

        Db::name("shopro_order_item")->where("order_id", 'not in', $order_id_arr)->delete();
        echo "d" . PHP_EOL;
        $user_list = Db::name("user")->select();
        $user_id_arr = array_column($user_list, 'id');
        echo "e" . PHP_EOL;
        Db::name("shopro_order")->where("user_id", 'not in', $user_id_arr)->delete();
        Db::name("shopro_order_item")->where("user_id", 'not in', $user_id_arr)->delete();
        Db::name("shopro_user_address")->where("user_id", 'not in', $user_id_arr)->delete();
        echo "f" . PHP_EOL;
        Db::name("share_user_flags")->where("user_id", 'not in', $user_id_arr)->delete();
        Db::name("pay_passwd")->where("user_id", 'not in', $user_id_arr)->delete();
        Db::name("share_user")->where("user_id", 'not in', $user_id_arr)->delete();
        echo "a" . PHP_EOL;
    }

    /**
     * @param $day
     * @return float
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 联创收益金额
     */
    public function rewardMoney($day = '')
    {

        $whereSql['one_day'] = ['IN', [0, 5]];
        $whereSql['status'] = ['IN', [1, 2]];
        $whereSql['pay_fee'] = ['>', 10];
        $whereSql['share_retreat'] = 0;
        if ($day) {
            $mon_count = Db::table('shopro_order')->field("count(id) as order_count,goods_id")->whereTime('paytime', $day)->where($whereSql)->group("goods_id")->select();
        } else {
            $mon_count = Db::table('shopro_order')->field("count(id) as order_count,goods_id")->where($whereSql)->group("goods_id")->select();
        }

        $creation_money_sum = 0;
        foreach ($mon_count as $k => $v) {
            $creation_money = Db::name("shopro_goods")->where(['id' => $v['goods_id']])->value("creation_money");
            $money = $creation_money * $v["order_count"];
            $creation_money_sum += $money;
            //echo $creation_money."_".$creation_money_sum."//";
        }
        return round($creation_money_sum, 2);
    }

    /**
     * 给中台同步用户数据
     */
    public function reUserDate()
    {
        //项目ID
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app_id = (new AppManage())->getAppId($url['value']);
        if ($app_id) {
            echo "项目ID:" . $app_id . PHP_EOL;

            echo "更新用户数据" . PHP_EOL;
            //获取最新更新时间
            $user_supdatetime = (new \app\admin\model\zhongtai\User())->getUpTime($app_id['id']);
            $user_up_data = Db::name("user")
                ->where('zt_time', '>=', $user_supdatetime)
                ->where('staff','<>',2)
                ->order("zt_time asc")->select();
            (new \app\admin\model\zhongtai\User())->upData($user_up_data, $app_id['id']);

            //订单
            echo "更新订单数据" . PHP_EOL;
            $order_supdatetime = (new \app\admin\model\zhongtai\ShoproOrder())->getUpTime($app_id['id']);
            $shopro_order_data = Db::name("shopro_order")
                ->where('zt_time', '>=', $order_supdatetime)
                ->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShoproOrder())->upData($shopro_order_data, $app_id['id']);

            //Recharge
            echo "更新充值数据" . PHP_EOL;
            $recharge_supdatetime = (new \app\admin\model\zhongtai\Recharge())->getUpTime($app_id['id']);
            $recharge_data = Db::name("recharge")->where('zt_time', '>=', $recharge_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\Recharge())->upData($recharge_data, $app_id['id']);

            //shopro_order_bill
            echo "更新订单分账数据" . PHP_EOL;
            $shopro_order_bill_supdatetime = (new \app\admin\model\zhongtai\ShoproOrderBill())->getUpTime($app_id['id']);
            $shopro_order_bill_data = Db::name("shopro_order_bill")->where('zt_time', '>=', $shopro_order_bill_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShoproOrderBill())->upData($shopro_order_bill_data, $app_id['id']);

            //shopro_order_bill_log
            echo "更新订单分账数据" . PHP_EOL;
            $shopro_order_bill_log_supdatetime = (new \app\admin\model\zhongtai\ShoproOrderBillLog())->getUpTime($app_id['id']);
            $shopro_order_bill_log_data = Db::name("shopro_order_bill_log")->where('zt_time', '>=', $shopro_order_bill_log_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShoproOrderBillLog())->upData($shopro_order_bill_log_data, $app_id['id']);

            //user_withdraw
            echo "更新提现数据" . PHP_EOL;
            $user_withdraw_supdatetime = (new \app\admin\model\zhongtai\UserWithdraw())->getUpTime($app_id['id']);
            $user_withdraw_data = Db::name("user_withdraw")->where('zt_time', '>=', $user_withdraw_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\UserWithdraw())->upData($user_withdraw_data, $app_id['id']);

            //shopro_goods
            echo "更新商品数据" . PHP_EOL;
            $shopro_goods_supdatetime = (new \app\admin\model\zhongtai\ShoproGoods())->getUpTime($app_id['id']);
            $shopro_goods_data = Db::name("shopro_goods")->where('zt_time', '>=', $shopro_goods_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShoproGoods())->upData($shopro_goods_data, $app_id['id']);

            //shopro_order_service
            echo "更新未收到货数据" . PHP_EOL;
            $shopro_order_service_supdatetime = (new \app\admin\model\zhongtai\ShoproOrderService())->getUpTime($app_id['id']);
            $shopro_order_service_data = Db::name("shopro_order_service")->where('zt_time', '>=', $shopro_order_service_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShoproOrderService())->upData($shopro_order_service_data, $app_id['id']);

            //union
            echo "更新未联创数据" . PHP_EOL;
            $union_supdatetime = (new \app\admin\model\zhongtai\Union())->getUpTime($app_id['id']);
            $union_data = Db::name("union")->where('zt_time', '>=', $union_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\Union())->upData($union_data, $app_id['id']);

            //user_stock_log
            echo "更新积分兑换股票数据" . PHP_EOL;
            $user_stock_log_supdatetime = (new \app\admin\model\zhongtai\UserStockLog())->getUpTime($app_id['id']);
            $user_stock_log_data = Db::name("user_stock_log")->where('zt_time', '>=', $user_stock_log_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\UserStockLog())->upData($user_stock_log_data, $app_id['id']);

            //vip_recharge_order
            echo "更新充值订单数据" . PHP_EOL;
            $vip_recharge_order_supdatetime = (new \app\admin\model\zhongtai\VipRechargeOrder())->getUpTime($app_id['id']);
            $vip_recharge_order_data = Db::name("vip_recharge_order")->where('zt_time', '>=', $vip_recharge_order_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\VipRechargeOrder())->upData($vip_recharge_order_data, $app_id['id']);

            //shopro_goods_sku
            echo "更新shopro_goods_sku数据" . PHP_EOL;
            $shopro_goods_sku_supdatetime = (new \app\admin\model\zhongtai\ShoproGoodsSku())->getUpTime($app_id['id']);
            $shopro_goods_sku_data = Db::name("shopro_goods_sku")->where('zt_time', '>=', $shopro_goods_sku_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShoproGoodsSku())->upData($shopro_goods_sku_data, $app_id['id']);

            //shopro_goods_sku_price
            echo "更新shopro_goods_sku_price数据" . PHP_EOL;
            $shopro_goods_sku_price_supdatetime = (new \app\admin\model\zhongtai\ShoproGoodsSkuPrice())->getUpTime($app_id['id']);
            $shopro_goods_sku_price_data = Db::name("shopro_goods_sku_price")->where('zt_time', '>=', $shopro_goods_sku_price_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShoproGoodsSkuPrice())->upData($shopro_goods_sku_price_data, $app_id['id']);

            //shopro_activity_goods_sku_price
            echo "更shopro_activity_goods_sku_price数据" . PHP_EOL;
            $shopro_activity_goods_sku_price_supdatetime = (new \app\admin\model\zhongtai\ShoproActivityGoodsSkuPrice())->getUpTime($app_id['id']);
            $shopro_activity_goods_sku_price_data = Db::name("shopro_activity_goods_sku_price")->where('zt_time', '>=', $shopro_activity_goods_sku_price_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShoproActivityGoodsSkuPrice())->upData($shopro_activity_goods_sku_price_data, $app_id['id']);

            //shopro_order_item
            echo "更新shopro_order_item数据" . PHP_EOL;
            $shopro_order_item_supdatetime = (new \app\admin\model\zhongtai\ShoproOrderItem())->getUpTime($app_id['id']);
            $shopro_order_item_data = Db::name("shopro_order_item")->where('zt_time', '>=', $shopro_order_item_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShoproOrderItem())->upData($shopro_order_item_data, $app_id['id']);
            //share_user_flags
            echo "更新share_user_flags数据" . PHP_EOL;
            $share_user_flags_supdatetime = (new \app\admin\model\zhongtai\ShareUserFlags())->getUpTime($app_id['id']);
            $share_user_flags_data = Db::name("share_user_flags")->where('zt_time', '>=', $share_user_flags_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShareUserFlags())->upData($share_user_flags_data, $app_id['id']);
            //shopro_order_item
            echo "更新user_money_log数据" . PHP_EOL;
            $user_money_log_supdatetime = (new \app\admin\model\zhongtai\UserMoneyLog())->getUpTime($app_id['id']);
            $user_money_log_data = Db::name("user_money_log")->where('zt_time', '>=', $user_money_log_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\UserMoneyLog())->upData($user_money_log_data, $app_id['id']);
            //shopro_order_item
            echo "更新user_score_log数据" . PHP_EOL;
            $user_score_log_supdatetime = (new \app\admin\model\zhongtai\UserScoreLog())->getUpTime($app_id['id']);
            $user_score_log_data = Db::name("user_score_log")->where('zt_time', '>=', $user_score_log_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\UserScoreLog())->upData($user_score_log_data, $app_id['id']);

            //shopro_order_item
            echo "更新user_advert_price_log数据" . PHP_EOL;
            $user_advert_price_log_supdatetime = (new \app\admin\model\zhongtai\UserAdvertPriceLog())->getUpTime($app_id['id']);
            $user_advert_price_log_item_data = Db::name("user_advert_price_log")->where('zt_time', '>=', $user_advert_price_log_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\UserAdvertPriceLog())->upData($user_advert_price_log_item_data, $app_id['id']);
            //shopro_order_item
            echo "更新share_goods_reward数据" . PHP_EOL;
            $share_goods_reward_supdatetime = (new \app\admin\model\zhongtai\ShareGoodsReward())->getUpTime($app_id['id']);
            $share_goods_reward_data = Db::name("share_goods_reward")->where('zt_time', '>=', $share_goods_reward_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShareGoodsReward())->upData($share_goods_reward_data, $app_id['id']);
        }
    }

    public function reOtherDate()
    {
        //项目ID
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app_id = (new AppManage())->getAppId($url['value']);
        if ($app_id) {
            echo "项目ID:" . $app_id . PHP_EOL;

            echo "更新分销用户数据" . PHP_EOL;
            //获取最新更新时间
            $share_user_supdatetime = (new \app\admin\model\zhongtai\ShareUser())->getUpTime($app_id['id']);
            $share_up_data = Db::name("share_user")->where('zt_time', '>=', $share_user_supdatetime)->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShareUser())->upData($share_up_data, $app_id['id']);
            $t = time() - 259200;
            //share_money
            echo "更新广告创收数据" . PHP_EOL;
            $share_money_supdatetime = (new \app\admin\model\zhongtai\ShareMoney())->getUpTime($app_id['id']);
            $share_money_data = Db::name("share_money")
                ->where('zt_time', '>=', $share_money_supdatetime)
                ->where('addtime', '>=', $t)
                ->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShareMoney())->upData($share_money_data, $app_id['id']);

            //share_reward
            echo "更新零批数据" . PHP_EOL;
            $share_reward_supdatetime = (new \app\admin\model\zhongtai\ShareReward())->getUpTime($app_id['id']);
            $share_reward_data = Db::name("share_reward")
                ->where('zt_time', '>=', $share_reward_supdatetime)
                ->where('addtime', '>=', $t)
                ->order('zt_time asc')->select();
            (new \app\admin\model\zhongtai\ShareReward())->upData($share_reward_data, $app_id['id']);
        }
    }

    /**
     * 注销用户删除好友关系
     */
    public function delUserf($user_id)
    {
        $share_data = Db::name("share_user")->where(["user_id" => $user_id])->find();
        //删除下级
        if ($user_id == 1) {
            $s = '%/' . $user_id;
        } else {
            $s = '%/' . $user_id . '/%';
        }
        $sonShareAll = Db::name("share_user")
            ->where('role_url', 'like', $s)
            ->select();
        if ($sonShareAll && count($sonShareAll) > 0) {
            foreach ($sonShareAll as $k1 => $v1) {
                (new IM())->del_relation($user_id, $v1['user_id']);
            }
        }
        //删除上级
        $low_arr = explode('/', trim($share_data['role_url'], '/'));
        $up_list = Db::name("user")->where('id', 'in', $low_arr)->field('id')->select();
        if ($up_list && count($up_list) > 0) {
            foreach ($up_list as $k => $v) {
                (new IM())->del_relation($user_id, $v['id']);
            }
        }
    }

    //添加用户  添加用户关系
    public function addUserf($user_id)
    {
        $share_data = Db::name("share_user")->where(["user_id" => $user_id])->find();
        //添加上级
        $low_arr = explode('/', trim($share_data['role_url'], '/'));
        $up_list = Db::name("user")->where('id', 'in', $low_arr)->field('id,nickname,mobile,avatar')->select();
        if ($up_list && count($up_list) > 0) {
            foreach ($up_list as $k => $v) {
                // (new app\api\controller())->getUserSig();
                (new IM())->make_relation($user_id, $v['id']);
            }
        }
    }
}
